package com.example.beatbox.model

import android.content.Context
import android.content.res.AssetManager
import android.media.AudioManager
import android.media.SoundPool
import android.util.Log
import java.io.IOException

class BeatBox(context: Context) {

    private var mAssetManager: AssetManager = context.assets
    private var mSoundPool: SoundPool? = null

    var sounds: MutableList<Sound> = mutableListOf()

    init {
        //兼容性考虑
        mSoundPool = SoundPool(MAX_SOUNDS, AudioManager.STREAM_MUSIC, 0)
        loadSounds()
    }

    companion object {
        const val TAG = "BeatBox"
        const val SOUNDS_FOLDER = "sample_sounds"
        const val MAX_SOUNDS = 5
    }

    private fun loadSounds() {
        val soundNames: Array<String>?
        try {
            soundNames = mAssetManager.list(SOUNDS_FOLDER)
            Log.i(TAG, "Found " + soundNames!!.size + " sounds")
        } catch (ioe: IOException) {
            Log.e(TAG, "Could not list assets", ioe)
            return
        }
        for (name in soundNames) {
            val path = "$SOUNDS_FOLDER/$name"
            val sound = Sound(path)
            load(sound)
            sounds.add(sound)

        }
    }

    private fun load(sound: Sound) {
        val fd = mAssetManager.openFd(sound.assetPath)
        val soundId = mSoundPool!!.load(fd, 1)
        sound.soundId = soundId
    }

    fun play(sound: Sound) {
        val soundId = sound.soundId
        soundId?.let { mSoundPool!!.play(soundId, 1.0f, 1.0f, 1, 0, 1.0f) }
    }

    fun release() {
        mSoundPool?.release()
    }
}